Adding Functionality To Existing Code At Exits

ABSTRACT

New code is added to existing object code in order to add new functionality. For example, a call to start a profiler function can be added at the beginning of a Java method and a call to stop the profiler function can be added at the exits of the Java method. A method may have many different exits. To insure that the profiler process is stopped regardless of which exit is performed, the byte code and exception table are modified.

CLAIM OF PRIORITY

This application is a continuation application of U.S. patentapplication Ser. No. 13/335,802, entitled “ADDING FUNCTIONALITY TOEXISTING CODE AT EXITS,” filed Dec. 22, 2011, which is a continuationapplication of U.S. patent application Ser. No. 12/400,586, entitled“ADDING FUNCTIONALITY TO EXISTING CODE AT EXITS,” filed Mar. 9, 2009,issued as U.S. Pat. No. 8,104,023 on Jan. 24, 2012, which is acontinuation application of U.S. patent application Ser. No. 09/795,901,entitled “ADDING FUNCTIONALITY TO EXISTING CODE AT EXITS,” filed Feb.28, 2001, issued as U.S. Pat. No. 7,512,935 on Mar. 31, 2009, all ofwhich are incorporated herein by reference in their entirety.

BACKGROUND OF THE INVENTION

Field of the Invention

The present invention is directed to technology for adding functionalityto existing code at exits.

Description of the Related Art

Performance profiling (or analysis) tools are popular tools used todebug software and to analyze an application's run time execution. Manyperformance profiling tools provide timing data on how long each method(or procedure or other process) is being executed, report how many timeseach method is executed and/or identify the function call architecture.Other functions can also be performed by various performance profilingtools. Some of the tools provide their results in text files or on amonitor. Other tools graphically display their results.

Many performance analysis tools perform their intended function byeither instrumenting source code or instrumenting object code. Objectcode can be generated by a compiler or an assembler. Alternatively,object code can be generated manually. Object code can be machineexecutable or suitable for processing to produce executable machinecode.

Instrumenting source code involves adding new instructions to sourcecode and/or modifying existing instructions in the source code.Instrumenting object code includes adding new instructions to the objectcode and/or modifying existing instructions in the object code.Instrumenting object code does not involve accessing the source code. Anexample of instrumenting object code can be found in U.S. patentapplication Ser. No. 09/137,666, filed on Aug. 20, 1998, by Lewis K.Cirne, incorporated herein by reference.

One problem with instrumenting source code to provide performanceprofiling is that the source code may not be available. Thus, manyperformance profiling tools will add the performance profilingfunctionality by instrumenting the object code.

One difficulty in instrumenting code is that a method (or other set ofinstructions) may include many exits. Consider the following code for amethod called “isNegative” which returns a Boolean value indicatingwhether a parameter is negative:

Boolean isNegative (int x) { if (x<0)    return true;    else returnfalse; }The above method includes at least two exit points. If the parameter xis less than 0, then the method exits at the “return true” instruction.If the parameter x is not less than 0, then the method exits at the“return false” instruction. Prior art systems that add performanceprofiling functionality will add new code to each of the exits in thecode. For example, code will be added to the return clause and the elseclause of the code above.

Adding performance profiling code to each of the instructions that canbe an exit has its drawbacks. First, the same code may be added inseveral places which can significantly increase the amount of code in anapplication. A significant increase in code may impact the performanceof the application and increase the chance of adding an error to theapplication. Additionally, the greater the number of exits, the greaterchance that the system adding performance profiling code will miss oneof the exits. Finally, not all of the exits are explicitly stated in thecode. For example, there can be errors or exceptions. When an error oran exception occurs, the normal flow of the method can be halted, inwhich case none of the explicit exits will be performed and an exitassociated with the error or exception will be performed. Previousperformance profiling tools have not adequately accounted for all thepossible exits in the software.

Therefore, what is needed is a system for adding performance profilingfunctionality to object code such that the new functionality is providedfor all (or almost all) exits of the method (or other set of code). Thisneed extends beyond just performance profiling tools. Thus, there is aneed to add functionality to existing object code at the exits for aparticular method (or other set of code) under consideration.

SUMMARY OF THE INVENTION

The present invention, roughly described, provides for a system foradding functionality to existing object code. The functionality is addedso that multiple exits are accounted for. That is, if a method hasmultiple exits, and it is desired that the added functionality includessome type of action at each of the exits, then code is added to theexisting object code such that the relevant action is performed at eachof the exits.

In one embodiment, new code is added to existing object code to add thenew functionality. For example, a call to start a profile action can beadded at the beginning of a method and calls to stop the profile actioncan be added at the various exits of the method. A method may have manyexits. The new code is added to insure that the profile action isstopped regardless of which of the exits is performed. In one embodimentusing Java byte code, the byte code for a method and the method'sexception table can be modified to implement the functions of the sourcecode statements “try” and “finally.”

In one implementation, the method of the present invention comprises thesteps of adding exit code to the existing object code and adding anentry to an exceptions data store pointing to the exit code. Onealternative also includes adding start code to the existing object code;however, some embodiments do not add start code. The start code, theexit code and the entry into the exceptions data store are used to addthe additional functionality. The additional functionality can be anyfunctionality desired to be added to the existing object code. Oneexample is to add performance profiling functionality.

In one embodiment, the start code starts an action and the exit codestops the action. The start code is positioned to be executed previousto the original byte code and the exit code is positioned to be executedsubsequent to the original byte code. The step of adding exit codeincludes adding an instruction to jump to the exit code from theoriginal byte code. In one implementation, the step of adding an entryin the exceptions data store includes adding a new entry into anexceptions table for that method. The new entry indicates a range ofindices of byte code, reference to the exit code and an indication thatthe entry pertains to all types of exceptions. In one implementation,the method described above is implemented using the Java programminglanguage.

The present invention can be implemented using hardware, software, or acombination of both hardware and software. The software used for thepresent invention is stored on one or more processor readable storagemedia including hard disk drives, CD-ROMs, DVDs, optical disks, floppydisks, tape drives, RAM, ROM or other suitable storage devices. Inalternative embodiments, some or all of the software can be replaced bydedicated hardware including custom integrated circuits, gate arrays,FPGAs, PLDs, special purpose computers and programmed general computers.Hardware that can be used for the present invention includes computers,handheld devices, telephones (e.g. cellular, Internet enabled, etc.),two-way pagers, etc. Some of these hardware devices include processors,memory, nonvolatile storage, input devices and output devices.

These and other objects and advantages of the present invention willappear more clearly from the following description in which thepreferred embodiment of the invention has been set forth in conjunctionwith the drawings.

BRIEF DESCRIPTION OF THE DRAWINGS

FIG. 1 is a block diagram depicting one embodiment of the code modifierof the present invention.

FIG. 2 is a flow chart describing one embodiment of the presentinvention.

FIG. 3 depicts a symbolic representation of a class data structure.

FIG. 4 is a flow chart describing one embodiment of the process ofmodifying existing object code.

FIG. 5 is a flow chart describing one embodiment of the process ofadding new exit byte code.

FIG. 6 is a block diagram of one embodiment of a computing system thatcan be used with the present invention.

DETAILED DESCRIPTION

FIG. 1 depicts code modifier 10 of the present invention. Code modifier10 includes at least two inputs and one output. The two inputs includeexisting object code and new functionality. The new functionalitydepicted in FIG. 1 can include additional methods, classes,instructions, etc. that add new functionality to the existing objectcode. In one embodiment, the new functionality implements a performanceprofiling tool. The output of code modifier 10 is the modified code. Inone embodiment, the modified code includes a combination of the existingobject code and the new functionality, with some subset of the existingobject code being edited. One implementation of the present inventionoperates on Java code. For example purposes, the remaining portions ofthis document provide examples using Java code. However, the presentinvention applies to other programming languages and formats as well.The examples below make use of the term “method,” which has a specificmeaning in reference to the Java programming language. For purposes ofthis document, “method” includes a Java method as well as other sets ofinstructions such as procedures, functions, routines, subroutines,sequences, etc.

In one embodiment of the present invention, new functionality is addedto a method such that all or part of the new functionality is executedupon exit from the method. Rather than add many copies of the exit codein different places, the present invention adds exit code using “try”and “finally” functionality. Consider the following example pseudo codefor a method called “foo” that includes a set of Java instructions:

public foo( )    {    [Java instructions]    }For example purposes, assume that a user wishes to add a profilingfunction to the method so that the user can determine how time elapseswhile the method is being performed. To do this, code has to be insertedinto the method to start a timer and code has to be inserted into themethod to stop the timer. After the timer is stopped, the amount of timemeasured will be reported to the user. The present invention,conceptually, adds code to the above method foo( )as follows:

public foo( )    {    start code;    try { [Java instructions] } finally   {    stop code    }    }As can be seen, new instructions represented by “start code” have beenadded to start the profiling function (e.g., start the timer).Additionally new code called “stop code” has been added that stops theprofiling function. Rather than physically insert copies of the stopcode at every possible explicit exit, the present invention conceptuallyencloses the [Java instructions] within a “try” block and places thestop code within a “finally” block. This implementation provides thatthe stop code will be performed regardless of the exit from the “try”block, including intentional exits and exceptions. Note that the“profiling function” can be a method, procedure, function, routine,subroutine, or any other set of code to implement profiling.

Many kinds of errors can cause exceptions. They range from serioushardware errors, such as a hard disk crash, to simple programmingerrors, such as trying to access an out-of-bounds array element. Whensuch an error occurs within a Java method, the method creates anexception object and hands it off to the run time system. The exceptionobject contains the information about the error, including its type and,possibly, the state of the program when the error occurred. The run timesystem is then responsible for finding some code to handle the error. InJava terminology, creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the run time system attempts to findsomething to handle the exception. The set of possible “somethings” tohandle the exception is the set of methods in the call stack of themethod where the error occurred. The run time system searches backwardsthrough the call stack, beginning with the method in which the erroroccurred, until it finds a method that contains an appropriate exceptionhandler. An exception handler is considered appropriate if the type ofexception thrown is the same type as the type of exception handled bythe handler. The exception bubbles up through the call stack until anappropriate handler is found and one of the calling methods handles theexception. The exception handler chosen is said to catch the exception.If the run time system exhaustively searches all the methods in the callstack without finding an appropriate exception handler, the threadterminates. A method can catch an exception by providing an exceptionhandler for that type of exception. One type of exception handler is the“catch” handler.

The first step in constructing an exception handler is to enclose thestatements that might throw an exception within a “try” block. Exceptionhandlers are associated with a “try” block by providing one or more“catch” blocks directly after the “try” block. Each “catch” block is anexception handler and handles the type of exception indicated by itsargument. Exception handling may optionally include a means for cleaningup before (possibly) allowing control to be passed to a different partof the program. This can be done by enclosing the clean up code within a“finally” block. Java's “finally” block provides a mechanism that allowsa method to clean up after itself regardless of what happens within thetry block. Typically, the “finally” block is used to close files orrelease other system resources.

To further understand the above discussion, below is example pseudo codefor a method called “exampleMethod.” This method receives an integerparameter, adds 1 to the integer parameter, and returns the sum:

public int exampleMethod(int x)    {    return x + 1;    }

The present invention will instrument this code, conceptually, byincluding a call to a tracer method, grouping the original instructionsfrom the method in a “try” block and adding a “finally” block with acode that stops the tracer:

 public int  exampleMethod(int x)     {     IMethodTracer tracer =AMethodTracer.loadTracer(       “com.introscope.agenttrace.MethodTimer”,        this,       “com.wily.example.ExampleApp”,        “exampleMethod”,       “name=Example Stat”);   try { return x + 1; } finally {   tracer.finishTrace( );    } }

IMethodTracer is an interface that defines a tracer for profiling.AMethodTracer is an abstract class that implements IMethodTracer.IMethodTracer includes the methods startTrace and finishTrace.AMethodTracer includes the methods startTrace, finishTrace, dostartTraceand dofinishTrace. The method startTrace is called to start a tracer,perform error handling and perform setup for starting the tracer. Theactual tracer is started by the method doStartTrace, which is called bystartTrace. The method finishTrace is called to stop a tracer, and toperform overhead and error handling. The method finishTrace callsdoFinishTrace to actually stop the tracer. Within AMethodTracer,startTrace and finishTracer are final and void methods; and doStartTraceand doFinishTrace are protected, abstract and void methods. Thus, themethods doStartTrace and do FinishTrace must be implemented insubclasses of AMethodTracer. Each of the subclasses of AMethodTracerimplement the actual tracers (e.g., timer, counter, etc.). The methodloadTracer is a static method that calls startTrace and includes fiveparameters. The first parameter, “com.introscope . . . ” is the name ofthe class that is intended to be instantiated that implements theinterface (e.g., the timer, which is a subclass of AMethodTracer). Thesecond parameter, “this” is the object being traced. The third parameter“com.wily.example . . . ” is the name of the class that the currentinstruction is inside of The fourth parameter, “exampleMethod” is thename of the method the current instruction is inside of The fifthparameter, “name= . . . ” is the name to record the statistics under.The original instruction (return x+1) is placed inside a “try” block.The code for stopping the tracer (a call to the static methodtracer.finishTrace) is put within the finally block.

The above example shows source code being instrumented. In oneembodiment, the present invention doesn't actually modify source code.Rather, the present invention modifies object code. The source codeexamples above are used for illustration to explain the concept of thepresent invention. The object code is modified conceptually in the samemanner that source code modifications are done above. That is, theobject code is modified to add the functionality of the “try” block and“finally” block.

In one embodiment of the present invention, the system will add code tothe existing object code to detect the start of a first method. Thedetection of the start of the method causes the starting of a countdowntimer. If the first method ends (or exits), the end of the first methodwill be detected and the timer will be terminated. If the first methoddoes not end in a reasonable amount of time, the timer will reach zeroand set off an alarm. Upon receiving an alarm, the system will concludethat the first method is lost. A lost method will be reported to theuser. In one implementation, the system will cease capturing profilinginformation for the lost method. In one implementation, the end of themethod is detected by code in the “finally” block, with the originalcode in the “try” block.

FIG. 2 is a flow chart depicting a process performed by the presentinvention to modify the existing object code and add the newfunctionality. In step 102, code modifier 10 receives the existingobject code. In step 104, code modifier 10 receives the newfunctionality. In step 106, the existing object code is modified. Instep 108, all or part of the new functionality is added to the code. Instep 110, the modified code (which includes the new functionality) isstored. In step 112, the modified code is run. In one embodiment, step112 includes running a software application with the performance profiletool. In embodiments that use functionality other than a performanceprofiler tool, step 112 includes executing that other functionality withthe original application.

As described above, step 102 includes receiving the existing objectcode. In one embodiment, the received code is stored in a class datastructure according to the Java Virtual Machine Specification. FIG. 3 isa symbolic representation of the class data structure which holds thecode for a class. The term code is used to refer to all of theinstructions, variables, definitions, pointers, addresses etc, that arestored in a class file and/or a class data structure. Magic item 202supplies the magic number identifying the class file. The values of theminor version 204 and major version 206 items are the minor and majorversion numbers of the compiler that produced the class file. Constantpool count item 208, which must be greater than zero, provides thenumber of entries in the constant pool. The constant pool entry at indexzero is included in the count but is not present in the constant pool. Aconstant pool index is considered valid if it is greater than zero andless than constant pool count 208. Constant pool 210 is a table ofvariable length structures representing various string constants, classnames, field names, integers, floating point numbers and other constantsthat are referred to within the class file structure and itssubstructures. Each of the constant pool entries at indices 1 throughconstant pool count-1 is a variable-length structure whose format isindicated by its first “tag” byte.

The value of access flags item 214 is a mask of modifiers used withclass and interface declarations. The access flags modifiers are public,final, super, interface and abstract. The value of this class item 214must be a valid index into the constant pool table. The constant poolentry at that index must be a CONSTANT_Class_info structure representingthe class or interface defined by this class file. For a class, thevalue of superclass item 216 either must be zero or must be a validindex into the constant pool. If the value of the superclass item isnonzero, the constant pool entry at that index must be aCONSTANT_Class_info structure representing the superclass of the classdefined by this class file. Neither the superclass nor any of itssuperclasses may be a final class. If the value of a superclass item iszero, then this class file must represent the class java.lang. Object,the only class or interface without a superclass.

The value of interfaces count item 218 provides the number of directsuperinterfaces of this class or interface type. Each value in theinterfaces array 220 must be a valid index into the constant pool. Theconstant pool entry at each value of interfaces[i], where 0≦i<interfacescount, must be a CONSTANT_Class_info structure representing an interfacewhich is a direct superinterface of this class or interface type. Thevalue of the fields count item 222 provides the number of field_infostructures in the fields table 224. The field info structures representall fields, both class variables and instance variables, declared bythis class or interface type. Each value in the fields must be avariable-length field_info structure giving a complete description of afield in the class or interface type. The fields table includes onlythose fields that are declared by this class or interface. It does notinclude item fields that are inherited from superclasses orsuperinterfaces.

The value of methods count item 226 provides the number of method_infostructures in methods table 228. Each entry in methods table 228 must bea variable-length method_info structure providing a complete descriptionof the Java Virtual Machine code for a method in the class or interface.The method_info structures represent all methods, both instance methodsand, for classes, class (static) methods, declared by this class orinterface type.

The value of the attributes count item 230 provides the number ofattributes in attributes table 232. Each entry in attributes table 232must be a variable-length attribute structure. A class data structurecan have any number of attributes associated with it. More informationabout ClassFile formats and the Java Virtual Machine can be found in TheJava Virtual Machine Specification, Tim Lindholm and Frank Yellin,Addison-Wesley, 1997, incorporated herein by reference.

All constant pool entries have the following general format:

cp_info {    tag;    info[ ]; }Each item in the constant pool must begin with a 1-byte tag indicatingthe type of cp_info entry. The contents of the info array varies withthe value of the tag. The valid tags and their values areCONSTANT_Class, CONSTANT_Fieldref, CONSTANT_Methodref,CONSTANT_InterfaceMethodref, CONSTANT_String, CONSTANT_Integer,CONSTANT_Float, CONSTANT_Long, CONSTANT_Double, CONSTANT_NameAndType,CONSTANT_Utf8. The following discussion explains the different types ofconstant pool entries.

The CONSTANT_Class info structure is used to represent a class or aninterface:

CONSTANT_Class_info {    u1 tag;    u2 name_index; }

The tag item has the value CONSTANT_Class. The value of the name_indexitem must be a valid index into the constant pool. The constant poolentry at that index must be a CONSTANT_Utf8_info structure representinga valid fully qualified Java class name that has been converted to theclass file's internal form. The values u1, u2 and u4 represent anunsigned one, two or four byte quantities, respectively.

Fields, methods, and interface methods are represented by similarstructures:

CONSTANT_Fieldref_info {    u1 tag;    u2 class_index;    u2name_and_type_index; } CONSTANT_Methodref_info {    u1 tag;    u2class_index;    u2 name_and_type_index; }CONSTANT_InterfaceMethodref_info {    u1 tag;    u2 class_index;    u2name_and_type_index; }

The tag item of a CONSTANT_Fieldref_info structure has the valueCONSTANT_Fieldref. The tag item of a CONSTANT_Methodref_info structurehas the value CONSTANT_Methodref. The tag item of aCONSTANT_InterfaceMethodref_info structure has the valueCONSTANT_InterfaceMethodref.

The value of the class_index item must be a valid index into theconstant pool. The constant pool entry at that index must be aCONSTANT_Class_info structure representing the class or interface typethat contains the declaration of the field or method.

The value of the name_and_type_index item must be a valid index into theconstant pool. The constant pool entry at that index must be aCONSTANT_NameAndType_info structure. This constant pool entry indicatesthe name and descriptor of the field or method.

The CONSTANT_String_info structure is used to represent constant objectsof the type java.lang.String:

CONSTANT_String_info {    u1 tag;    u2 string_index; }

The tag item of the CONSTANT_String_info structure has the valueCONSTANT_String. The value of the string_index item must be a validindex into the constant pool. The constant pool entry at that index mustbe a CONSTANT_Utf8_info structure representing the sequence ofcharacters to which the java.lang.String object is to be initialized.

The CONSTANT_Integer_info and CONSTANT_Float_info structures representfour-byte numeric (int and float) constants:

   CONSTANT_Integer_info {    u1 tag;    u4 bytes; } CONSTANT_Float_info{    u1 tag;    u4 bytes; }

The tag item of the CONSTANT_Integer_info structure has the valueCONSTANT_Integer. The tag item of the CONSTANT_Float info structure hasthe value CONSTANT_Float. The bytes item of the CONSTANT_Integer_infostructure contains the value of the int constant. The bytes of the valueare stored in big-endian (high byte first) order. The bytes item of theCONSTANT_Float_info structure contains the value of the float constantin IEEE 754 floating-point “single format” bit layout. The bytes of thevalue are stored in big-endian (high byte first) order, and are firstconverted into an int argument.

The CONSTANT_Long_info and CONSTANT_Double_info represent eight-bytenumeric (long and double) constants:

CONSTANT_Long_info {    u1 tag;    u4 high_bytes;    u4 low_bytes; }CONSTANT_Double_info {    u1 tag;    u4 high_bytes;    u4 low_bytes; }

All eight-byte constants take up two entries in the constant pool. If aCONSTANT_Long_info or CONSTANT_Double_info structure is the item in theconstant pool at index n, then the next valid item in the pool islocated at index n+2. The constant pool index n+1 must be consideredinvalid and must not be used.

The tag item of the CONSTANT_Long_info structure has the valueCONSTANT_Long. The tag item of the CONSTANT Double info structure hasthe value CONSTANT_Double. The unsigned high_bytes and low_bytes itemsof the CONSTANT_Long structure together contain the value of the longconstant ((long)high_bytes<<32)+low_bytes, where the bytes of each ofhigh_bytes and low_bytes are stored in big-endian (high byte first)order. The high_bytes and low_bytes items of the CONSTANT_Double_infostructure contain the double value in IEEE 754 floating point “doubleformat” bit layout. The bytes of each item are stored in big-endian(high byte first) order.

The CONSTANT_NameAndType_info structure is used to represent a field ormethod, without indicating which class or interface type it belongs to:

CONSTANT_NameAndType_info {    u1 tag;    u2 name_index;    u2descriptor_index; }

The tag item of the CONSTANT_NameAndType_info structure has the valueCONSTANT_NameAndType. The value of the name index item must be a validindex into the constant pool. The constant pool entry at that index mustbe a CONSTANT_Utf8_info structure representing a valid Java field nameor method name. The value of the descriptor_index item must be a validindex into the constant pool. The constant_pool entry at that index mustbe a CONSTANT_Utf8_info structure representing a valid Java fielddescriptor or method descriptor.

The CONSTANT_Utf8_info structure is used to represent constant stringvalues:

CONSTANT_Utf8_info {    u1 tag;    u2 length;    bytes [length]; }

The tag item of the CONSTANT_Utf8_info structure has the valueCONSTANT_Utf8_. The value of the length item gives the number of bytesin the bytes array (not the length of the resulting sring). The stringsin the CONSTANT_Utf8_info structure are not null-terminated.

Each field is described by a variable-length field_info structure. Theformat of this structure is

field_info {    u2 access_flags;    u2 name_index;    u2descriptor_index;    u2 attributes_count;    attribute_info attributes         [attributes_count]; }

The value of the access_flags item is a mask of modifiers used todescribe access permission to and properties of a field. Theaccess_flags modifiers are public, private, protected, static, final,volatile and transient.

The value of the name_index item must be a valid index into the constantpool. The constant pool entry at that index must be a CONSTANT_Utf8_infostructure which must represent a valid Java field name. The value of thedescriptor_index item must be a valid index into the constant pool. Theconstant pool entry at that index must be a CONSTANT_Utf8 structurewhich must represent a valid Java field descriptor. The value of theattributes_count item indicates the number of additional attributes ofthis field. Each value of the attributes table must be a variable-lengthattribute structure. A field can have any number of attributesassociated with it.

Each method is described by a variable-length method_info structure. Thestructure has the following format:

method_info {    u2 access_flags;    u2 name_index;    u2descriptor_index;    u2 attributes_count;    attribute_info attributes      [attributes_count]; }

The value of the access_flags item is a mask of modifiers used todescribe access permission to and properties of a method. Theaccess_flags modifiers are public, private, protected, static, final,synchronized, native and abstract. The value of the name_index item mustbe a valid index into the constant pool. The constant pool entry at thatindex must be a CONSTANT_Utf8_info structure representing a valid Javamethod name. The value of the descriptor_index item must be a validindex into the constant pool. The constant pool entry at that index mustbe a CONSTANT_Utf8_info structure representing a valid Java methoddescriptor. The value of the attributes_count item indicates the numberof additional attributes of this method. Each value of the attributestable must be a variable-length attribute structure. A method can havecode attributes and exception attributes.

Attributes have the following general format:

attribute_info {    u2 attribute_name_index;    u4 attribute_length;   u1 info [attribute_length]; }

The attribute_name_index must be a valid unsigned 16 bit index into theconstant pool of the class. The constant pool entry at theattribute_name_index must be a CONSTANT_Utf8_info structure representingthe name of the attribute. The value of the attribute_length itemindicates the length of the subsequent information in bytes. The lengthdoes not include the initial 6 bytes that contain theattribute_name_index and attribute_length items.

The Java virtual machine recognizes code and exception attributes for amethod info structure. The Code attribute is a variable-length attributeused in the attributes table of method_info structures. A Code attributecontains the Java virtual machine instructions and auxiliary informationfor a single Java method, instance initialization method or classinterface initialization method. Every Java virtual machineimplementation must recognize code attributes. There must be exactly oneCode attribute in each method info structure.

The Code attribute has the following format:

Code_attribute {       u2 attribute_name_index;       u4attribute_length;       u2 max_stack;       u2 max_locals;       u4code_length       u1 code[code_length];       u2 exeption_table_length;      {   u2 start_pc;          u2 end_pc;          u2 handler_pc;         u2 catch_type;   } exception_table [exception_table_length];  u2 attributes_count;   attribute_info attributes [attributes_count];

The attribute_name_index must be a valid index into the constant pooltable. The constant pool entry at the index must be a CONSTANT_Utf8_infostructure representing the string “Code.” The value of theattribute_length item indicates the length of the attribute, excludingthe initial six bytes. The value of the max_stack item gives the maximumnumber of words on the operand stack at any point during execution ofthis method. The value of the max_locals item gives the number of localvariables used by this method, including the parameters passed to themethod on invocation. The index of the first local variable is 0. Thevalue of the code_length item gives the number of bytes in the codearray for this method. The code array stores the actual bytes of codethat implement the method. The exception_table_length provides thenumber of entries in the exception_table.

Each entry in the exception_table array describes one exception handlerin the code array. Each exception_table entry contains the followingitems: start_pc, end_pc, handler_pc and catch_type. The values ofstart_pc and end_pc indicate the ranges in the code array at which theexception handler is active. The value of start_pc must be a valid indexinto the code array of the opcode of an instruction. The value of end_pcmust be a valid index into the code array of the opcode of aninstruction, or must be equal to code_length, the length of the codearray. The value of start_pc must be less than the value of end_pc.Start_pc is inclusive and end_pc is exclusive. The value of handler_pcindicates the start of the exception handler code, is a valid index intothe code array, is the index of the opcode of an instruction, and isless than the value of code_length. If the value of catch_type is non 0,then catch_type must be a valid index into the constant pool table. Theconstant pool entry at that index must be a CONSTANT_Class_infostructure representing a class of exceptions that this exception handleris designed to catch. This class must be the class Throwable or one ofthe subclasses. The exception handler will be called only if the thrownexception is an instance of the given class or one of its subclasses. Ifthe value of the catch type item is 0, this exception handler is calledfor all exceptions—this is used to implement “finally.” The value of theattributes_count item indicates the number of attributes in the codeattribute. Each value of the attributes table must be a variable-lengthstructure.

The Exceptions attribute is a variable-length attribute used in theattributes table of a method_info structure. The Exceptions attributeindicates which checked exceptions a method may throw. There must beexactly one exceptions attribute in each method_info structure. Theexceptions attribute has the following format:

Exceptions_attribute {    u2 attribute_name_index;    u4attribute_length;    u2 number_of_exceptions;    U2exception_index_table [number_of_exceptions];

The value of attribute_name_index must be a valid index into theconstant pool table. The constant pool entry at that index must be aCONSTANT_Utf8_info structure representing the string “Exceptions.” Thevalue of the attribute_length item indicates the attribute length,including the initial 6 bytes. The value of the number_of_exceptionsitem indicates the number of entries in the exception_index_table. Eachnon-zero value in the exception_index_table array must be a valid indexinto the constant pool to a CONSTANT_Class_info structure representing aclass type that this method is prepared to throw.

The class file structure of FIG. 3 described above is the structure thatis modified in steps 106 and 108 of FIG. 2. Specifically, at least thecode array of the code_attribute is modified, the exception_table_lengthis modified and the exception table is modified, as described below.Formats and file structures other than that depicted in FIG. 3 can alsobe used.

FIG. 4 is a flowchart describing the process of modifying the existingobject code (step 106) and adding new function to the code (step 108 ofFIG. 2). The process of FIG. 4 is performed for one method on a datastructure like that of FIG. 3. The process of FIG. 4 would be repeatedfor each method that needs to be instrumented. In other embodiments, theprocess of FIG. 4 can operate on data structures other than that of FIG.3.

In step 302 of FIG. 4, the system accesses the beginning of the bytecode for a particular method. In one implementation, step 302 includesaccessing the first element in the code array of the code_attribute ofthe method info structure. In step 304, the indices for the byte codeare adjusted. That is, the system knows it needs to add the start codeand knows how many bytes the start code occupies. These bytes willeventually be added to the top of the array. Therefore, the remaininginstructions need to be moved (change index) to make room for the newinstructions. If the start code needs 8 bytes, then the indices for theoriginal code needs to be adjusted to reflect the displacement by 8bytes. Additionally, all references to byte code within an instructionmust also be adjusted; for example, the pointer reference for a jump orbranch instruction must be adjusted. In step 306, the new start code isadded to the code array. As discussed above, the example discussedherein is using Java byte code. Thus, step 306 includes adding new Javabyte code to the beginning of the code array. In step 308, the systemaccesses the end of the byte code, which in one embodiment is the end ofthe code array. In step 310, the new exit byte code is added at the endof the code array. In some embodiments, a portion of the exit byte codeis added at other points in the code array. Additionally, otheralternatives include adding the exit byte code at locations other thanthe end of the byte code.

In step 312 of FIG. 4, the exception table is adjusted. That is, becausethe indices of the byte codes changed, the values of start_pc, end_pcand handler_pc may need change for existing exception handlers. Asdescribed above, each entry in the exception table indicates a range ofcode in the code array that pertain to the particular exception handler.Because the code indices were shifted, the indices in the exceptiontable must also shift accordingly. If the location of the exceptionhandler code moved in the code array, then handler_pc must also changeaccordingly. Step 312 can also include adjusting other tables in theclass file, as appropriate to the particular implementation. In oneembodiment, of her tables that need to be adjusted can be removed.

In step 314, a new entry is added to the exception table. This new entrycorrelates to the new “finally” block. The new entry has a catch_type ofzero, indicating it is for all exceptions. Additionally, the new entryin the exceptions table will be added to the end of the exceptionstable. The start_pc and end_pc the new entry would be set to include theoriginal Java byte code for the method being instrumented. The value ofthe handler_pc for the new entry would point to the new byte code addedin step 310.

FIG. 5 is a flowchart describing more detail of the process of addingnew exit byte code (step 310 of FIG. 4). In step 402, new code is addedto the code array to account for the situation where there is noexception. That is, the original Java method instructions are performedwithout any exceptions. After the original instructions are performed,the new exception handler code must be executed. The original code isinstrumented to include a jump to the byte code for the exceptionhandler corresponding to the “finally” block. In step 404, new byte codeis added to the code array that accounts for the situation when thereare exceptions. In step 406, the code for the exception handler isadded.

To better understand the present invention, an example is provided. Thisexample explains one embodiment for performing the present invention.Described above is example pseudo code for “exampleMethod.” Below is thepseudo object code (converted to a human readable form) forexampleMethod (which does not have an exceptions table):

Max stack size: 2 Max local variables: 2 Code size: 4  0 iload_1  1iconst_1  2 iadd  3 ireturn

The pseudo object code for exampleMethod includes four instructions. Thefirst instruction (iload_1) pushes the parameter x onto the stack. Thesecond instruction (iconst_1) pushes a constant (1) onto the stack. Thethird instruction (iadd) adds the top two quantities on the stack. Thefourth instruction returns whatever is on top of the stack, which inthis case is the sum from the previous instruction. The code above is anexample of the existing object code that would be an input to codemodifier 10. In one example, code modifier 10 modifies this existingobject code as follows:

Max stack size: 9 Max local variables: 6 Code size: 48 0 ldc #42 <String “com.wily.introscope.agent.trace.MethodTimer”> 2 aload_0 3 ldc #56<String “com.wily.example.ExampleApp”> 5 ldc #58 <String“exampleMethod”> 7 ldc #60 <String “name=Example Stat”> 9   invokestatic     #48     <Methodcom.wily.introscope.agent.trace.IMethodTracercom.wily.introscope.agent.trace.AMethodTracer.loadTracer(java.lang.String, java.lang.Object, java.lang.String,java.lang.String, java.lang.String)> 12 astore 4 14 nop 15 nop 16iload_1 17 iconst_1 18 iadd 19 istore 5 21 jsr 36 24 iload 5 26 nop 27ireturn 28 astore_3 29 jsr 36 32 aload_3 33 athrow 34 nop 35 nop 36astore_2 37 aload 4 39 invokeinterface (args 1) #54    <InterfaceMethod    void IMethodTracer_finishTrace( )> 44 ret 2 46 nop 47 nop

Exception Table start_pc end_pc handler_pc catch_type 16 28 28 0Code modifier 10 modified the original object code to add start code andexit code. The first section of the modified code, identified by indices0-15, corresponds to the source code “IMethodTracertracer=AMethodTracer.loadTracer( . . . parameter . . . ).” These bytecodes push the parameters, call AMethodTracer.loadTracer, and store theresult in a local variable. The nops at the end are just to make codingeasier. In one embodiment, the longest sequence needed to generate is 16bytes long. In one implementation, the code modifier always adds 16bytes. Sometimes not all 16 bytes are used, so the code is padded withnops.

Section two of the modified code corresponds to instructions withindices 16, 17 and 18. These three instructions correspond to existingobject code for implementing “x=x+1.”

The third section of the modified code corresponds to instructions fromindices 19-27, and is performed in the case where there are noexceptions. This code calls the “finally handler.” Basically, the codeof the third section sets aside the computed value (puts it into atemporary, here, local number 5). The code then jumps to the finallyhandler (jsr 36). When control returns back from the finally handler,the code gets the answer out of local number 5 and puts it back on thestack. Then, it returns.

Section four corresponds to code with indices 28-35. This is the “catchall exceptions” handler. Any exceptions not otherwise handled would jumpto this code. This code jumps to the “finally handler” (jsr 36). Thissequence of instructions saves the pending exception object, jumps tothe “finally handler,” restores the pending exception object, and thenre-throws the pending exception object.

Section five of the code, corresponding to indices 36-47, represents the“finally handler” itself. This code stores its own return address, loadsthe tracer out of local 4 (where it put it back at index 12), calls thefinish trace handler, and returns back to where it came from.

The example above also includes an exception table which has one entry.This entry indicates that for code between indices 16 and 28, if thereis any type of exception go to the handler starting at index 28. Notethat instruction 28 is the “catch all exceptions handler” describedabove.

Note that ranges of instructions protected by two different exceptionhandlers always are either completely disjoint, or else one is asubrange of the other. If there are multiple entries in the exceptiontable, the first, innermost, applicable exception handler in theexception table is chosen to handle the exception. The code for thatexception handler performs its intended function and then makes asubroutine call to the “finally handler.”

FIG. 6 illustrates a high level block diagram of a computer system whichcan be used for various components of the present invention. Thecomputer system of FIG. 6 includes a processor unit 550 and main memory552. Processor unit 550 may contain a single microprocessor, or maycontain a plurality of microprocessors for configuring the computersystem as a multi-processor system. Main memory 552 stores, in part,instructions and data for execution by processor unit 550. If the systemof the present invention is wholly or partially implemented in software,main memory 552 can store the executable code when in operation. Mainmemory 552 may include banks of dynamic random access memory (DRAM) aswell as high speed cache memory.

The system of FIG. 6 further includes a mass storage device 554,peripheral device(s) 556, user input device(s) 560, output devices 558,portable storage medium drive(s) 562, a graphics subsystem 564 and anoutput display 566. For purposes of simplicity, the components shown inFIG. 6 are depicted as being connected via a single bus 568. However,the components may be connected through one or more data transportmeans. For example, processor unit 550 and main memory 552 may beconnected via a local microprocessor bus, and the mass storage device554, peripheral device(s) 556, portable storage medium drive(s) 562, andgraphics subsystem 64 may be connected via one or more input/output(I/O) buses. Mass storage device 554, which may be implemented with amagnetic disk drive or an optical disk drive, is a non-volatile storagedevice for storing data and instructions for use by processor unit 550.In one embodiment, mass storage device 554 stores the system softwarefor implementing the present invention for purposes of loading to mainmemory 552.

Portable storage medium drive 562 operates in conjunction with aportable non-volatile storage medium, such as a floppy disk, to inputand output data and code to and from the computer system of FIG. 6. Inone embodiment, the system software for implementing the presentinvention is stored on such a portable medium, and is input to thecomputer system via the portable storage medium drive 562. Peripheraldevice(s) 556 may include any type of computer support device, such asan input/output (I/O) interface, to add additional functionality to thecomputer system. For example, peripheral device(s) 556 may include anetwork interface for connecting the computer system to a network, amodem, a router, etc.

User input device(s) 560 provides a portion of a user interface. Userinput device(s) 560 may include an alpha-numeric keypad for inputtingalpha-numeric and other information, or a pointing device, such as amouse, a trackball, stylus, or cursor direction keys. In order todisplay textual and graphical information, the computer system of FIG. 6includes graphics subsystem 564 and output display 566. Output display566 may include a cathode ray tube (CRT) display, liquid crystal display(LCD) or other suitable display device. Graphics subsystem 564 receivestextual and graphical information, and processes the information foroutput to display 566. Additionally, the system of FIG. 6 includesoutput devices 558. Examples of suitable output devices includespeakers, printers, network interfaces, monitors, etc.

The components contained in the computer system of FIG. 6 are thosetypically found in computer systems suitable for use with the presentinvention, and are intended to represent a broad category of suchcomputer components that are well known in the art. Thus, the computersystem of FIG. 6 can be a personal computer, mobile computing device,workstation, server, minicomputer, mainframe computer, or any othercomputing device. The computer can also include different busconfigurations, networked platforms, multi-processor platforms, etc.Various operating systems can be used including Unix, Linux, Windows,Macintosh OS, Palm OS, and other suitable operating systems.

The foregoing detailed description of the invention has been presentedfor purposes of illustration and description. It is not intended to beexhaustive or to limit the invention to the precise form disclosed. Manymodifications and variations are possible in light of the aboveteaching. The described embodiments were chosen in order to best explainthe principles of the invention and its practical application to therebyenable others skilled in the art to best utilize the invention invarious embodiments and with various modifications as are suited to theparticular use contemplated. It is intended that the scope of theinvention be defined by the claims appended hereto.

I claim:
 1. A method implemented on one or more machines for modifyingexisting object code, the method comprising: adding exit code to saidexisting object code; and adding a new entry in an exceptions data storefor said existing object code, said new entry points to said exit code.2. A method according to claim 1, further comprising: creating a path tosaid exit code from said existing object code.
 3. A method according toclaim 2, wherein: said creating a path includes adding a jumpinstruction.
 4. A method according to claim 1, wherein: said exit codeis part of a profiling process; and said method further comprisesperforming said profiling process.
 5. A method according to claim 1,further comprising: adding start code to said existing object code.
 6. Amethod according to claim 5, wherein: said existing object code includesa method having original byte code; said start code is to be performedupon starting said method; said start code is a call to a start method;said exit code is a call to an exit method; said start method starts aprofiling process; and said exit method stops a profiling process.
 7. Amethod according to claim 5, wherein: said existing object code includesa method having original byte code; and said adding start code includesadding new byte code to said method and adjusting indices for saidoriginal byte code, said new byte code is positioned to be executedprior to said original byte code.
 8. A method according to claim 7,wherein: said start code starts a profiling process; said exit codestops a profiling process; said exit code is positioned to be executedsubsequent to said original byte code; said exceptions data store is anexception table for said method; and said adding a new entry in saidexceptions data store includes adding said new entry into said exceptiontable for said method, said new entry indicates a range of indicescorresponding to said original byte code, said new entry includes areference to said exit code and said new entry indicates that said newentry pertains to all types of exceptions.
 9. A method according toclaim 1, wherein: said new entry includes a reference to said exit codeand indicates that said new entry pertains to two or more types ofexceptions.
 10. A method according to claim 1, wherein: said new entryincludes a reference to said exit code and indicates that said new entrypertains to all types of exceptions.
 11. A method according to claim 1,wherein: said existing object code includes a method; and said adding anew entry in said exceptions data store includes adding said new entryfor said method, said new entry indicates a range of indicescorresponding to said method, said new entry includes a reference tosaid exit code and said new entry indicates that said new entry pertainsto multiple types of exceptions.
 12. A method according to claim 1,further comprising: storing said exit code.
 13. A method according toclaim 1, wherein: said existing object code includes a Java method; saidexit code is Java; and said exceptions data store is a Java exceptiontable for said Java method.
 14. A method according to claim 1, whereinsaid adding exit code includes: adding new finalization code; adding newcode that calls said new finalization code if no exceptions occur; andadding a new exception handler, said new exception handler is performedif an otherwise unhandled exception occurs, said new exception handlercalls said new finalization code.
 15. A method according to claim 14,wherein: said adding a new entry in an exceptions data store includesadding a new entry in an exceptions table, said new entry includes areference to a portion of said existing object code and a reference tosaid new exception handler.
 16. A method according to claim 1, wherein:said adding a new entry in an exceptions data store creates a groupingof a portion of said existing object code and references a portion ofsaid exit code that is to be performed if an exception occurs duringexecution of said portion of said existing object code.
 17. A methodaccording to claim 1, wherein: said adding exit code and adding a newentry include adding try and finally functionality to said existingobject code.
 18. The method of claim 1, wherein said adding exit codeand adding a new entry are performed automatically.
 19. One or moreprocessor readable storage devices having processor readable codeembodied thereon, said processor readable code for programming one ormore processors to perform a method comprising: adding exit code toexisting object code, and adding a new entry in an exceptions data storepointing to said exit code.
 20. One or more processor readable storagedevices according to claim 19, wherein: said existing object codeincludes a method having original byte code; said method furthercomprises adding start code to said existing object code, said addingstart code includes adding new byte code to said method and adjustingindices for said original byte code; said start code starts a profilingprocess; said exit code stops a profiling process; said exit code ispositioned to be executed subsequent to said original byte code; saidexceptions data store is an exception table for said method; and saidadding a new entry in said exceptions data store includes adding a newentry into said exception table for said method, said new entryindicates a range of indices corresponding to said original byte code,said new entry includes a reference to said exit code and said new entryindicates that said new entry pertains to all types of exceptions. 21.One or more processor readable storage devices according to claim 19,wherein: said existing object code includes a method; and said adding anew entry in said exceptions data store includes adding said new entryfor said method, said new entry indicates a range of indicescorresponding to said method, said new entry includes a reference tosaid exit code and said new entry indicates that said new entry pertainsto multiple types of exceptions.
 22. One or more processor readablestorage devices according to claim 19, wherein said adding exit codeincludes: adding new finalization code; adding new code that calls saidnew finalization code if no exceptions occur; and adding a new exceptionhandler, said new exception handler is performed if an otherwiseunhandled exception occurs, said new exception handler calls said newfinalization code, said adding a new entry in an exceptions data storeincludes adding a new entry in an exceptions table, said new entryincludes a reference to a portion of said existing object code and areference to said new exception handler.
 23. One or more processorreadable storage device according to claim 19, wherein: said adding anew entry in an exceptions data store comprises creating a new groupingof at least a portion of said existing object code; said adding exitcode includes adding new finalization code for said grouping, adding newcode that calls said new finalization code if no exceptions occur, andadding new code that is performed if an exception occurs, said new codethat is performed if an exception occurs calls said new finalizationcode.
 24. One or more processor readable storage device according toclaim 23, wherein said adding a new entry in an exceptions data storecomprises: adding a new entry in an exceptions table that includes areference to said grouping and a reference to said new finalizationcode.
 25. A method implemented on one or more machines for addingfunctionality to existing object code, the method comprising: adding newexit functionality to said existing object code; creating a grouping ofall or a portion of said existing object code; and associating saidgrouping of said existing object code with at least a portion of saidnew exit functionality that is to be performed if an exception occursduring execution of said grouping of said existing object code.
 26. Amethod according to claim 25, wherein: said method includes adding startfunctionality to said existing object code; said existing object codeincludes a method having original byte code; said start functionality isto be performed upon starting said method; said new exit functionalityis performed upon exiting said method; said start functionality is acall to a start method; said new exit functionality is a call to an exitmethod; said start method starts a profiling process; and said exitmethod stops a profiling process.
 27. A method according to claim 25,wherein: said method includes adding start functionality to saidexisting object code; said existing object code includes a method havingoriginal byte code; and said adding start functionality includes addingnew byte code to said method and adjusting indices for said originalbyte code, said new byte code is positioned to be executed prior to saidoriginal byte code.
 28. A method according to claim 27, wherein: saidstart functionality starts a profiling process; said new exitfunctionality stops a profiling process; said new exit functionality ispositioned to be executed subsequent to said original byte code; saidadding new exit functionality includes adding an instruction to jump tonew exit code from said original byte code; and said associatingincludes adding a new entry to an exception table, said new entryindicates a range of indices corresponding to said original byte code,said new entry includes a reference to said new exit functionality andsaid new entry indicates that said new entry pertains to all types ofexceptions.
 29. A method according to claim 25, wherein: said creating agrouping and associating implement try and finally functionality.
 30. Amethod according to claim 25, wherein: said existing object codeincludes a method; and said associating includes adding a new entry intoan exceptions data store for said method, said new entry indicates arange of indices corresponding to said original method, said new entryincludes a reference to exit code and said new entry indicates that saidnew entry pertains to multiple types of exceptions.
 31. A methodaccording to claim 25, wherein said adding new exit functionalityincludes: adding new finalization code; adding new code that calls saidnew finalization code if no exceptions occur; and adding a new exceptionhandler, said new exception handler is performed if an otherwiseunhandled exception occurs, said new exception handler calls said newfinalization code.
 32. A method according to claim 31, wherein: saidcreating and associating includes adding a new entry in an exceptionstable, said new entry includes a reference to said grouping and areference to said new exception handler.
 33. A method according to claim25, wherein: said adding, creating and associating include adding tryand finally functionality to said existing object code.
 34. One or moreprocessor readable storage devices having processor readable codeembodied thereon, said processor readable code for programming one ormore processors to perform a method comprising: adding new exitfunctionality to existing object code; creating a grouping of all orpart of said existing object code; and associating said new exitfunctionality as a clean up process for said all or part of saidexisting object code grouped together.
 35. One or more processorreadable storage devices according to claim 34, wherein: said methodfurther comprises adding start functionality to said existing objectcode; said existing object code includes a method having original bytecode; said adding start functionality includes adding new byte code tosaid method and adjusting indices for said original byte code, said newbyte code is positioned to be executed prior to said original byte code;said start functionality starts a profiling process; said new exitfunctionality stops a profiling process; said new exit functionality ispositioned to be executed subsequent to said original byte code; andsaid associating includes adding a new entry to an exception table, saidnew entry indicates a range of indices corresponding to said originalbyte code, said new entry includes a reference to said new exitfunctionality and said new entry indicates that said new entry pertainsto all types of exceptions.
 36. One or more processor readable storagedevices according to claim 34, wherein: said creating a grouping andassociating implement try and finally functionality.
 37. One or moreprocessor readable storage devices according to claim 34, wherein: saidexisting object code includes a method; and said associating includesadding a new entry into an exceptions data store for said method, saidnew entry indicates a range of indices corresponding to said originalbyte code, said new entry includes a reference to said new exitfunctionality and said new entry indicates that said new entry pertainsto multiple types of exceptions.
 38. An apparatus, comprising: one ormore storage devices; and one or more processors in communication withsaid one or more storage devices, said one or more processors programmedto perform a method comprising: accessing existing object code; andadding try and finally functionality to said existing object code. 39.An apparatus according to claim 38, wherein said adding try and finallyfunctionality includes: adding new finalization code; adding new codethat calls said new finalization code if no exceptions occur; adding anew exception handler, said new exception handler is performed if anotherwise unhandled exception occurs, said new exception handler callssaid new finalization code; and adding a new entry in an exceptionstable, said new entry includes a reference to a portion of said existingobject code and a reference to said new exception handler.
 40. Anapparatus according to claim 39, wherein: said new entry indicates thatsaid new entry pertains to multiple types of exceptions.